package com.task.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.task.common.entity.custom.Task;
import com.task.common.entity.custom.TaskEval;
import com.task.common.entity.custom.TaskUser;
import com.task.common.entity.custom.model.CreateTaskModel;
import com.task.common.entity.custom.model.QueryTaskModel;
import com.task.common.entity.custom.vo.TaskVO;
import com.task.common.entity.sys.SysUser;
import com.task.common.util.excelstyle.CustIExcelExportStyler;
import com.task.common.util.model.FieldUtil;
import com.task.common.util.model.ModelUtil;
import com.task.common.util.security.SecurityUtils;
import com.task.common.util.string.StringUtils;
import com.task.mapper.TaskEvalMapper;
import com.task.mapper.TaskMapper;
import com.task.mapper.TaskUserMapper;
import com.task.mapper.UserMapper;
import com.task.service.ITaskService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Huzz
 * @since 2022-05-21
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Autowired
    private TaskUserMapper taskUserMapper;

    @Autowired
    private TaskEvalMapper taskEvalMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean deleteTask(Integer id) {
        return this.baseMapper.deleteById(id) > 0;
    }


    @Override
    public List<Task> findCustTaskList(QueryTaskModel model) {
        // 查找用户所关联的任务id集合
        Integer userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<TaskUser> taskUserWrapper = new LambdaQueryWrapper<>();
        taskUserWrapper.eq(TaskUser::getUserId, userId);
        List<TaskUser> taskUsers = taskUserMapper.selectList(taskUserWrapper);
        if (taskUsers.isEmpty()) {
            return new ArrayList<>();
        }
        List<Integer> taskIds = taskUsers.stream().map(TaskUser::getTaskId).collect(Collectors.toList());

        QueryWrapper<Task> wrapper = getTaskQueryWrapper(model);
        wrapper.lambda().in(Task::getId, taskIds);

        // 返回用户的任务
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public boolean submitTaskModification(Integer taskId, Integer schedule, Integer status) {

        Task task = new Task();
        task.setId(taskId);
        task.setSchedule(schedule);
        task.setStatus(status);
        return this.baseMapper.updateById(task) > 0;
    }

    @Override
    public boolean updateEval(Integer taskId, Integer userId, String evaluation, String grade) {
        Task task = this.baseMapper.selectById(taskId);
        if (task.getStatus() == 4) {
            TaskEval taskEval = new TaskEval();
            taskEval.setTaskId(taskId);
            taskEval.setUserId(userId);
            taskEval.setEvaluation(evaluation);
            taskEval.setGrade(grade);
            LambdaQueryWrapper<TaskEval> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TaskEval::getTaskId, taskId);
            wrapper.eq(TaskEval::getUserId, userId);
            return taskEvalMapper.update(taskEval, wrapper) > 0;
        }
        return false;
    }

    @Override
    public boolean taskEval(Integer taskId, Integer userId, String evaluation, String grade) {
        Task task = this.baseMapper.selectById(taskId);
        if (task.getStatus() == 4) {
            TaskEval taskEval = new TaskEval();
            taskEval.setTaskId(taskId);
            taskEval.setUserId(userId);
            taskEval.setEvaluation(evaluation);
            taskEval.setGrade(grade);
            return taskEvalMapper.insert(taskEval) > 0;
        }
        return false;
    }

    @Override
    public boolean taskTransfer(Integer taskId, Integer oldUserId, Integer newUserId) {
        LambdaQueryWrapper<TaskUser> wrapper = new LambdaQueryWrapper<>();
        TaskUser taskUser = new TaskUser();
        taskUser.setTaskId(taskId);
        taskUser.setUserId(newUserId);

        return taskUserMapper.update(taskUser, wrapper) > 0;
    }

    @Override
    public void exportTask(HttpServletRequest request, HttpServletResponse response, QueryTaskModel model) {
        QueryWrapper<Task> itemQueryWrapper = getTaskQueryWrapper(model);

        List<Task> data = this.baseMapper.selectTaskList(itemQueryWrapper);
        List<TaskVO> taskVOS = getTaskVOS(data);

        ExportParams exportParams = new ExportParams();
        exportParams.setTitle("任务管理业务列表");
        exportParams.setSheetName("任务管理");
        // 设置样式
        exportParams.setStyle(CustIExcelExportStyler.class);

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TaskVO.class, taskVOS);

        String fileName = String.format("任务管理_%d.xls", System.currentTimeMillis());
        response.setHeader("Content-Disposition", "attachment;Filename=" + fileName);
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        try {
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Map<String, String>> importTask(MultipartFile multipartFile) {
        List<Map<String, String>> resultData = new ArrayList<>();

        List<Task> list = new ArrayList<>();
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(1);
        importParams.setHeadRows(1);
        try {
            InputStream inputStream = multipartFile.getInputStream();
            list = ExcelImportUtil.importExcel(inputStream, Task.class, importParams);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list.isEmpty()) {
            Map<String, String> result = new HashMap<>();
            result.put("ERROR", "导入失败, 请检查文件格式后重试");
            resultData.add(result);
            return resultData;
        }
        // 初始化信息
        for (Task task : list) {
            task.setDel(0);
            FieldUtil.setCreatedAndUpdateField(task);
        }
        if (this.saveBatch(list)) {
            Map<String, String> result = new HashMap<>();
            result.put("OK", "导入成功");
            resultData.add(result);
            return resultData;
        }
        return resultData;
    }

    @Override
    public IPage<TaskVO> findTaskList(Integer pageNum, Integer pageSie, QueryTaskModel model) {
        QueryWrapper<Task> wrapper = getTaskQueryWrapper(model);

        IPage<Task> page = this.baseMapper.selectTaskList(new Page<>(pageNum, pageSie), wrapper);

        List<Task> list = page.getRecords();
        List<TaskVO> dataList = getTaskVOS(list);

        IPage<TaskVO> resultPage = new Page<>();
        resultPage.setRecords(dataList);
        resultPage.setTotal(page.getTotal());
        resultPage.setPages(page.getPages());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setSize(page.getSize());

        return resultPage;
    }

    private List<TaskVO> getTaskVOS(List<Task> list) {
        List<TaskVO> dataList = (List<TaskVO>) ModelUtil.toArrayListEntityStatic(list, TaskVO.class);
        for (TaskVO taskVO : dataList) {
            // 是否延期
            taskVO.setPostpone("尚未延期");
            if (taskVO.getFinishedTime() != null && taskVO.getEndTime().before(taskVO.getFinishedTime())) {
                taskVO.setPostpone("任务已延期");
            }
            // 设置用户信息
            QueryWrapper<TaskUser> wp = new QueryWrapper<>();
            wp.lambda().eq(TaskUser::getTaskId, taskVO.getId());
            List<TaskUser> taskUsers = taskUserMapper.selectList(wp);
            if (!taskUsers.isEmpty()) {
                List<Integer> userIds = taskUsers.stream().map(TaskUser::getUserId).collect(Collectors.toList());
                QueryWrapper<SysUser> userWp = new QueryWrapper<>();
                userWp.lambda().in(SysUser::getId, userIds);
                taskVO.setUserBaseList(userMapper.selectUserBaseList(userWp));
            }
        }
        return dataList;
    }

    /**
     * 条件拼接
     *
     * @param model
     * @return
     */
    private QueryWrapper<Task> getTaskQueryWrapper(QueryTaskModel model) {
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(model.getName())) {
            wrapper.lambda().eq(Task::getName, model.getName());
        }
        if (!StringUtils.isEmpty(model.getPrincipalId())) {
            wrapper.lambda().eq(Task::getPrincipalId, model.getPrincipalId());
        }
        if (null != model.getItemId()) {
            wrapper.lambda().eq(Task::getItemId, model.getItemId());
        }
        if (!StringUtils.isEmpty(model.getDescription())) {
            wrapper.lambda().like(Task::getDescription, model.getDescription());
        }
        if (null != model.getStatus()) {
            wrapper.lambda().eq(Task::getStatus, model.getStatus());
        }
        if (!StringUtils.isEmpty(model.getStartTime())) {
            wrapper.apply("UNIX_TIMESTAMP(start_time) >= UNIX_TIMESTAMP('" + model.getStartTime() + "')");
        }
        if (!StringUtils.isEmpty(model.getEndTime())) {
            wrapper.apply("UNIX_TIMESTAMP(end_time) <= UNIX_TIMESTAMP('" + model.getEndTime() + "')");
        }
        wrapper.lambda().ne(Task::getDel, 1);
        wrapper.lambda().orderByAsc(Task::getPriority);
        return wrapper;
    }

    @Override
    public boolean updateTask(Integer id, Task model) {
        model.setId(id);
        if (StringUtils.isEmpty(model.getDescription())) {
            model.setDescription(null);
        }
        if (StringUtils.isEmpty(model.getName())) {
            model.setName(null);
        }
        FieldUtil.setUpdateField(model);
        return this.baseMapper.updateById(model) > 0;
    }

    @Override
    public boolean createTask(CreateTaskModel model) {
        Task task = (Task) ModelUtil.toEntityStatic(model, Task.class);
        FieldUtil.setCreatedAndUpdateField(task);
        task.setSchedule(0);
        task.setDel(0);
        // 分配给员工
        if (this.baseMapper.insert(task) > 0) {
            TaskUser taskUser = new TaskUser();
            taskUser.setTaskId(task.getId());
            taskUser.setUserId(model.getUserId());

            return taskUserMapper.insert(taskUser) > 0;
        }
        return false;
    }
}
